<?php
/***
 * 素材后台Service
 *
 *
 * @author    lanhongjie <lanhj@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */

namespace App\Services\SourcePicService;


use App\Services\ImgServices\ImgTool;
use App\Services\PreferentialService\PreferentialBackService;
use App\Services\TagService\TagService;
use App\Services\TagService\TagTool;
use App\Services\Tool\GeneralTool;
use App\Services\UserService\UserTool;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use App\Services\Tool\Jpush\JpushTool;
class SourcePicBakService
{
    protected $imgTool;
    protected $sourcePicTool;
    protected $preferentialBackSer;
    protected $userTool;
    protected $tagTool;
    protected $tagService;
    /**
     * SourcePicBakService constructor.
     */
    public function __construct(ImgTool $imgTool,
                                PreferentialBackService $preferentialBackSer,
                                SourcePicTool $sourcePicTool,
                                TagService $tagService,
                                UserTool $userTool,
                                TagTool $tagTool)
    {
        $this->imgTool=$imgTool;
        $this->sourcePicTool=$sourcePicTool;
        $this->preferentialBackSer=$preferentialBackSer;
        $this->userTool=$userTool;
        $this->tagTool=$tagTool;
        $this->tagService=$tagService;
    }

    /***
     * 添加素材数据到数据库
     * @param array $data
     * @return bool
     */
    public function addSourcePic(array $data){
        try{
            $image=$data['image'];
            if(isset($data['preferential_begin_time'])){
                $preferential['begin_time']=$data['preferential_begin_time'];
                unset($data['preferential_begin_time']);
            }
            if(isset($data['preferential_price'])){
                $preferential['preferential_price']=$data['preferential_price'];
                unset($data['preferential_price']);
            }
            if(isset($data['preferential_end_time'])){
                $preferential['preferential_end_time']=$data['preferential_end_time'];
                unset($data['preferential_end_time']);
            }
            if(isset($data['preferential_stock'])){
                $preferential['preferential_stock']=$data['preferential_stock'];
                unset($data['preferential_stock']);
            }
            $has_preferential=$data['add_preferential'];
            unset($data['image']);
            unset($data['add_preferential']);
            if(!empty($image)){
                $img_path=$this->imgTool->imgSave($image,2);
            }else{
                return false;
            }
            if(empty($img_path)){
                return false;
            }
            if(!empty($img_path)){
                $data['original_image']=$img_path;
                $image_thumbnail_url=$this->imgTool->getImgThumbByImgPath($img_path,600,600,true);
                $image_small_url=$this->imgTool->getImgThumbByImgPath($img_path,300,300,true);
                $data['thumbnail']=$image_thumbnail_url;
                $data['small_image']=$image_small_url;
            }
            $source_pic_id=GeneralTool::only_no();
            $data['source_pic_id']=$source_pic_id;
            $res=self::saveSourcePicDB($data);
//            if($res&&($has_preferential===1)){
//                $preferential['resources_id']=$source_pic_id;
//                $preferential['resources_type']=1;
//                $save_preferential=$this->preferentialBackSer->savePreferentialToDB($preferential);
//            }
            return $res;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 素材删除
     * @param $source_pic_id
     * @return bool
     */
    public function delSourcePicBySourcePicId($source_pic_id){
        try{
            DB::beginTransaction();
            $source_pic=$this->sourcePicTool->getSourcePicBySourcePicId($source_pic_id);
            //需要判断并发推送
            //删除关联
            $this->tagTool->delTagResourceMapsByResourceId($source_pic_id,1);
            $num=DB::table('source_pics')
                ->where(array('source_pic_id'=>$source_pic_id,'state'=>1))
                ->update(array(
                    'state'=>0,
                    'updated_at'=>time()
                ));
            return ($num===0)?false:true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 上传简单素材信息
     * @param array $data
     * @return bool
     */
    public function uploadSourcePicSimpleInfo(array $data){
        try{
            $image=$data['file'];
            $tag_id=$data['tag_id'];
            unset($data['file']);
            unset($data['tag_id']);
            if(!empty($image)){
                $img_path=$this->imgTool->imgSave($image,2);
            }else{
                return false;
            }
            if(empty($img_path)){
                return false;
            }
            if(!empty($img_path)){
                $data['original_image']=$img_path;
                $image_thumbnail_url=$this->imgTool->getImgThumbByImgPath($img_path,600,600,true);
                $image_small_url=$this->imgTool->getImgThumbByImgPath($img_path,300,300,true);
                $data['thumbnail']=$image_thumbnail_url;
                $data['small_image']=$image_small_url;
            }else{
                return false;
            }
            DB::beginTransaction();
            $source_pic_id=GeneralTool::only_no();
            $data['source_pic_id']=$source_pic_id;
            $res=self::saveSourcePicDB($data);
            $tag_resource_map['resource_id']=$source_pic_id;
            $tag_resource_map['tag_id']=$tag_id;
            $tag_resource_map['app_id']=1;
            $save_tag_resource_map=TagTool::saveTagResourceMaps($tag_resource_map);
            return ($res)?true:false;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }
    /***
     * 保存素材数据
     * @param array $data
     * @return bool
     */
    private function saveSourcePicDB(array $data){
            $data['state']=1;
            $data['created_at']=time();
            $data['updated_at']=time();
            $res=DB::table('source_pics')->insert($data);
            return ($res==1)?true:false;
    }

    /***
     * 素材批量更新
     * @param array $data
     * @return bool
     */
     public function bachUpdateSourcePic(array $data){
         try{
             $type=$data['type'];
             $type_value=$data['type_value'];
             $data_arr=$data['data_arr'];
             $tag_exist=TagTool::tagExistByTagId($type_value,1);
             if(!is_array($data_arr)){
                 return false;
             }
             DB::beginTransaction();
             if($tag_exist){
                 foreach ($data_arr as $resource_id){
                     $resource['tag_id']=$type_value;
                     $resource['resource_id']=$resource_id;
                     $resource['app_id']=1;
                     TagTool::saveTagResourceMaps($resource);
                 }
             }
             return true;
         }catch (\Exception $e){
             DB::rollback();
             Log::info($e);
             return false;
         }finally{
             DB::commit();
         }
     }
    /***
     * 更新素材
     * @param array $data
     * @return bool
     */
    public function updateSourcePicDB(array $data){
        try{
            if(!isset($data['source_pic_id'])){
                return false;
            }
            $source_pic_id=$data['source_pic_id'];
            $data['updated_at']=time();
            $res=DB::table('source_pics')
                ->where(array('source_pic_id'=>$source_pic_id))
                ->update($data);
            return ($res==1)?true:false;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    /***
     * 图片上传校验
     * @param $data
     * @return array
     */
    public function imgSaveValidator($data){
        $rules=array(
            'file' => 'required|mimes:png,gif,jpeg,jpg,bmp',
        );
        $validator = Validator::make($data, $rules);
        if ($validator->fails()) {
            if ($validator->errors()->first('file')) {
                return GeneralTool::createResult('', 'M00000');
            }else{
                return GeneralTool::createResult('', 'M00001');
            }
        }
    }

    /***
     * 添加素材标签
     * @param array $input
     * @return bool
     */
    public function addSourcePicTag(array $input)
    {
        try{
            $tag=array();
            if(isset($input['tag_name'])&&!empty($input['tag_name'])){
                $tag['name']=$input['tag_name'];
            }
            if(!isset($input['description'])||empty($input['description'])){
                $tag['description']='';
            }else{
                $tag['description']=$input['description'];
            }
            //        是否共享
            if(isset($input['is_share'])){
                $is_share=$input['is_share'];
                $tag['is_share']=$is_share;
            }
            $tag['type']=2;
            $tag['state']=1;
            $tag['created_at']=time();
            $tag['updated_at']=time();
            DB::beginTransaction();
            $tag_id=DB::table('tags')->insertGetId($tag);
            return true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return false;
        }finally{
            DB::commit();
        }
    }

    /***
     * 素材审核不通过
     * @param $source_pic_id
     * @param $msg
     * @return bool
     */
    public function auditNotPass($source_pic_id,$msg){
        $source_pic=$this->getSourcePic($source_pic_id);
        if(empty($source_pic)){
            return false;
        }
        $message='很遗憾，你的素材没能通过审核，具体原因：\n'.$msg;
        if($source_pic->user_id!=0){
            $user_type=$this->userTool->userType($source_pic->user_id);
            if(!empty($user_type)){
                JpushTool::push(
                    '【审核未通过】你有⼀个素材没有通过审核>>查看详情',
                    0,
                    $source_pic->user_id.'',
                    ['title'=>'审核未通过',
                        'user_id'=>$source_pic->user_id,
                        'class'=>'system_notification',
                        'type'=>1,
                        'jump_value'=>'',
                        'template_no'=>'4',
                        'message'=>$message,
                        'images'=>[['original_image'=>$source_pic->original_image,'thumbnail'=>$source_pic->small_image]]
                    ]);
            }
        }

        $data['source_pic_id']=$source_pic_id;
        $data['audit_state']=3;
        $data['is_shelves']=0;
        $data['audit_value']='审核未通过';
        $res=$this->updateSourcePicDB($data);
        return $res;

    }
    public function auditPass($source_pic_id,$audit_state){
        $source_pic=$this->getSourcePic($source_pic_id);
        if(empty($source_pic)){
            return false;
        }
        $push_msg='';
        $message='';
        if($source_pic->price==0){
            $price='免费';
        }else{
            $price='¥'.GeneralTool::priceFormat($source_pic->price);
        }
        if($audit_state==2){
            $data['audit_value']='审核通过';
            $title='审核通过';
            if($source_pic->is_shelves==1){
                $push_msg.='【审核通过】你的素材已通过审核，当前默认上架';
                $message.='你的素材已通过审核，当前默认上架';
            }else{
                $push_msg.='【审核通过】你的素材已通过审核，当前默认上架';
                $message.='素材已上架\n出售价格：'.$price.'\n';
                if($source_pic->end_time==0){
                    $message.='下架时间：暂无';
                }else{
                    $message.='下架时间：'.date('Y年m月d日 H:i',$source_pic->end_time);
                }
            }
        }else{
            $data['audit_value']='审核中';
            $push_msg='【素材审核中】你有⼀个素材审核中>>查看详情';
            $title='素材审核中';
        }
        if($source_pic->user_id!=0){
            $user_type=$this->userTool->userType($source_pic->user_id);
            if(!empty($user_type)){
                JpushTool::push(
                    $push_msg,
                    0,
                    $source_pic->user_id.'',
                    ['title'=>$title,
                        'user_id'=>$source_pic->user_id,
                        'class'=>'system_notification',
                        'type'=>1,
                        'jump_value'=>'',
                        'template_no'=>'4',
                        'message'=>$message,
                        'images'=>[['original_image'=>$source_pic->original_image,'thumbnail'=>$source_pic->small_image]]
                    ]);
            }
        }
        if($audit_state==1){
            $data['is_shelves']=0;
        }else{
            // 默认审核通过就上架
            $data['is_shelves']=1;
        }
        $data['begin_time']=time();
        $data['source_pic_id']=$source_pic_id;
        $data['audit_state']=$audit_state;
        $res=$this->updateSourcePicDB($data);
        $audit_record['source_pic_id']=$source_pic_id;
        $audit_record['audit_state']=2;
        $audit_record['audit_value']='已通过';
        $audit_record['pass_time']=time();
        $audit_record['no_pass_reason']='';
        $this->saveSourcePicAuditRecord($audit_record);
        return $res;
    }

    /***
     * 更改素材是否显示
     * @param $source_pic_id
     * @param $is_show
     * @return bool
     */
    public function changeShow($source_pic_id,$is_show){
        $source_pic=$this->getSourcePic($source_pic_id);
        if(empty($source_pic)){
            return false;
        }
        $data['begin_time']=time();
        $data['source_pic_id']=$source_pic_id;
        $data['is_show']=$is_show;
        $res=$this->updateSourcePicDB($data);
        return $res;
    }
    /***
     * 保存审核记录
     * @param array $data
     * @return bool
     */
    public function saveSourcePicAuditRecord(array  $data){
        if(empty($data)){
            return false;
        }
        $data['state']=1;
        $data['created_at']=time();
        $data['updated_at']=time();
        $res=DB::table('source_pic_audit_records')->insert($data);
        return ($res==1)?true:false;
    }
    /**
     * 检查Tag是不是已经存在
     * @param $tag_name
     * @return bool
     */
    public function checkTagNameExist($tag_name){
        return $this->sourcePicTool->checkTagNameExist($tag_name);
    }

    /***
     * 判断素材是不是存在
     * @param $source_pic_id
     * @param int $state
     * @return bool
     */
    public function sourcePicExistBySourcePicId($source_pic_id,$state=1)
    {
        if($state===1){
            $num=DB::table('source_pics')->where(array('state'=>1,'source_pic_id'=>$source_pic_id))->count();
        }else{
            $num=DB::table('source_pics')->where(array('source_pic_id'=>$source_pic_id))->count();
        }

        return ($num===0)?false:true;
    }

    /***
     * 获取素材列表
     * @param $tag_id
     * @param int $per_page
     * @return mixed
     */
    public function getSourcePicList($conditions,$per_page=10)
    {
        $audit_state=isset($conditions['audit_state'])?$conditions['audit_state']:-1;
        $is_shelves=isset($conditions['is_shelves'])?$conditions['is_shelves']:-1;
        $platform=isset($conditions['platform'])?$conditions['platform']:-1;
        $query=DB::table('source_pics')->where(array('state'=>1));
        if(($audit_state===0)||($audit_state==1)||($audit_state==2)||($audit_state==3)){
            $query->where('audit_state',$audit_state);
        }
        if(($is_shelves===0)||($is_shelves==1)){
            $query->where('is_shelves',$is_shelves);
        }
        if($platform!==-1){
            $query->where('platform',$platform);
        }
        $source_pics=$query->orderBy('updated_at','DESC')->paginate($per_page);
        $source_pics->appends(['is_shelves' => $is_shelves,'platform' => $platform,'audit_state' => $audit_state,])
                    ->render();
        return $source_pics;
    }
    public function getSourcePicByTagId($tag_id)
    {
        if(empty($tag_id)||!is_int($tag_id)){
            return false;
        }
        $all_source_pic_ids=DB::table('source_pics')
            ->where('state',1)
            ->pluck('source_pic_id')
            ->toArray();
        $query= DB::table('tag_resource_maps')->where(array('state'=>1,'app_id'=>1));
        $query->where('tag_id',$tag_id);
        $query->whereIn('resource_id',$all_source_pic_ids);
        $query->orderby('sort','ASC');
        $query->orderby('updated_at','DESC');
        $source_pics=$query->select(
            'id as tag_resource_map_id',
            'updated_at',
            'sort',
            'resource_id as source_pic_id'
        )->paginate(10);
        $source_pics->appends(['id' => $tag_id])->render();
        return $source_pics;
    }

    /***
     * 获取素材简要信息
     * @param $source_pic_id
     * @return null
     */
    public function getSourcePicSimpleInfoBySourcePicId($source_pic_id)
    {
        if(empty($source_pic_id)){
            return null;
        }
        $source_pic=DB::table('source_pics')
            ->where(array('state'=>1,'source_pic_id'=>$source_pic_id))
            ->select('small_image','is_show','user_id','user_id','audit_state','audit_value','is_shelves')
            ->first();
        return $source_pic;
    }
    /***
     * 获取素材标签
     * @param array $data
     * @return bool|null
     */
    public function getSourcePicTagList(array $data){
        $per_page=(!isset($data['per_page'])||!is_int($data['per_page']))?10:$data['per_page'];
        $data['per_page']=$per_page;
        $where_arr=array();
        $where_arr['app_id']=1;
        $data['where']=$where_arr;
        $data['orderByKeyword']='sort';
        $data['orderByRule']='ASC';
        $tags=TagTool::pagedAccessToTags($data);
        if (empty($tags)){
            return false;
        }
        foreach ($tags as $tag){
            $tag->has_sub_tag=TagTool::hasSubTagByTagId($tag->id,1);
        }
        return $tags;
    }
    public  static function getSourcePic($source_pic_id)
    {
        $source_pic_id=trim($source_pic_id);
        if(empty($source_pic_id)){
            return null;
        }
        $source_pic=DB::table('source_pics')->where(array('source_pic_id'=>$source_pic_id))
            ->first();
        return $source_pic;
    }

    /***
     * 添加
     * @param array $data
     * @return bool
     */
    public function addTagTempMap(array $data){
        try{
            $resource['tag_id']=$data['tag_id'];
            $resource['resource_id']=$data['resource_id'];
            $resource['app_id']=1;
            $res=TagTool::saveTagResourceMaps($resource);
            return $res;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
}